//
//  BBSViewController.m
//  论坛
//
//  Created by 张育铭 on 2019/10/19.
//  Copyright © 2019 赢辉网络科技有限公司. All rights reserved.
//
 
#import "BBSViewController.h"
#import "ToolControl.h"
#import "CJTableViewModel.h"
#import "BBSViewListCell.h"
#import "BBSMessageViewController.h"
#import "BBSSenderViewController.h"
#import "BBSMineSenderViewController.h"
#import "GHOCNavBarView.h"

@interface BBSViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView  *tableView;
/// 热门
@property (nonatomic,strong) NSMutableArray *hotDataArray;
/// 列表
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,assign) NSInteger totalCount;


@end

@implementation BBSViewController {
    CGFloat theHeight;

}

- (instancetype)init {
    self.hidesBottomBarWhenPushed = YES;
    return [super init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(244, 244, 244);
    [self setNavBarTitle:@"健康论坛"];
    [self setNavBarRightBtn:[GHOCNavBarView createImgNaviBarBtnByImgNormal:@"luntanshare" imgHighlight:nil target:self action:@selector(rightBarButtonClick:)]];
    
    _totalCount = 1;
    [self setupRefreshData];
    
    theHeight = theIsIphoneX? 83: 49;
    [self downLodingDate];
    
    self.tableView.tableHeaderView = [self headView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:[self footView]];
     
}

- (void)downLodingDate {
    /// 热门
    [[HTTPManager sharedInstance] GetWithPath:@"/frontend/news/forum/hot" parametersDict:nil sucessBlock:^(NSURLSessionDataTask *operation, id responseObject) {
//        NSLog(@"%@",responseObject);
        if ([responseObject[@"code"] integerValue] == 0) {
            [self.hotDataArray removeAllObjects];
            for (NSDictionary *dic in responseObject[@"data"][@"items"]) {
                CJTableViewModel *model = [[CJTableViewModel alloc]initHotWithDict:dic];
                [self.hotDataArray addObject:model];
            }
        }
        /// 列表  @{@"page_size":@"20",@"page":[NSString stringWithFormat:@"%ld",(long)self.totalCount],@"categories":@"1|2|3"}
        [[HTTPManager sharedInstance] GetWithPath:@"/frontend/news/forum/list" parametersDict:nil sucessBlock:^(NSURLSessionDataTask *operation, id responseObject) {
//            NSLog(@"%@",responseObject);
            if ([responseObject[@"code"] integerValue] == 0) {
                if (self.totalCount == 1) {
                    [self.dataArray removeAllObjects];
                    [self.tableView.mj_header endRefreshing];
                } else {
                    [self.tableView.mj_footer endRefreshing];
                }
                for (NSDictionary *dic in responseObject[@"data"][@"items"]) {
                    CJTableViewModel *model = [[CJTableViewModel alloc]initWithDict:dic];
                    [self.dataArray addObject:model];
                }
                if (self.dataArray.count > 0) {
                    [self.tableView reloadData];
                }
            } else {
                self.totalCount = 1;
            }
        } failtBlock:^(NSURLSessionDataTask *operation, id error) {
        }];
    } failtBlock:^(NSURLSessionDataTask *operation, id error) {
    }];
}

- (UIView*)headView {
    UIView *headBackView = [[UIView alloc] initWithFrame:CGRectMake(-1, 0, SCREEN_WIDTH+2, 180 + 19 + 10)];
    headBackView.layer.borderWidth = .5;
    headBackView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    UIImageView *lineImageOne = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180)];
    lineImageOne.image = imageName(@"bbs_main");
    [headBackView addSubview:lineImageOne];
    
    UIImageView *lineImageTwo = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-140)/2, 180 + 5, 140, 19)];
    lineImageTwo.image = imageName(@"bbs_title");
    [headBackView addSubview:lineImageTwo];
  
    return headBackView;
}

- (UIView*)footView {
    UIView *headBackView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-theHeight, SCREEN_WIDTH, theHeight)];
    headBackView.backgroundColor = [UIColor whiteColor];
    
    /// 返回
    UIButton *homeBtn = [ToolControl creatButtonWithFrame:CGRectMake(0, 0, 60, 49) Title:nil Font:18 image:imageName(@"bbs-tohome") target:self selector:@selector(changeMessageBtnClick:)];
    [headBackView addSubview:homeBtn];
   
    /// 线
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(60, 10, 1, 30)];
    line.backgroundColor = [UIColor lightGrayColor];
    [headBackView addSubview:line];
    
    UIButton *changeBtn = [ToolControl creatButtonWithFrame:CGRectMake(61, 0, (SCREEN_WIDTH-120)/2, 49) Title:@" 板块专区" Font:18 image:imageName(@"bbs-model") target:self selector:@selector(changeMessageBtnClick:)];
    [headBackView addSubview:changeBtn];
    
    UIButton *senderMS = [ToolControl creatButtonWithFrame:CGRectMake(((SCREEN_WIDTH-120)/2) + 60, 0, (SCREEN_WIDTH-120)/2, 49) Title:@" 我要发帖" Font:18 image:imageName(@"bbs-fatie") target:self selector:@selector(changeMessageBtnClick:)];
    [headBackView addSubview:senderMS];
     
    /// 线
    UIImageView *lineOne = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60, 10, 1, 30)];
    lineOne.backgroundColor = [UIColor lightGrayColor];
    [headBackView addSubview:lineOne];
    
    UIButton *mineBtn = [ToolControl creatButtonWithFrame:CGRectMake(SCREEN_WIDTH-60, 0, 50, 49) Title:nil Font:18 image:imageName(@"bbs-toperson") target:self selector:@selector(changeMessageBtnClick:)];
    [headBackView addSubview:mineBtn];
    
    homeBtn.tag   = 10001;
    changeBtn.tag = 10002;
    senderMS.tag  = 10003;
    mineBtn.tag   = 10004;
    
    return headBackView;
}

- (void)rightBarButtonClick:(UIButton *)sender {
    
}

- (void)changeMessageBtnClick:(UIButton*)sender {
    if (sender.tag == 10001) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    if (sender.tag == 10002) {
        
    }
    if (sender.tag == 10003) {
        BBSSenderViewController *view = [BBSSenderViewController new];
        [self.navigationController pushViewController:view animated:YES];
    }
    if (sender.tag == 10004) {
        [self.navigationController pushViewController:[BBSMineSenderViewController new] animated:YES];
    }
}
/// 设置头视图
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 40;
    }
    return 10;
}
/// 头视图风格
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [UIView new];
    if (section == 0) {
        view.backgroundColor = [UIColor whiteColor];
        UILabel *label = [ToolControl creaImagetTitleLabelWithFrame:CGRectMake(30, 0, SCREEN_WIDTH, 30) theImageStr:@"bbs-hot" theImageWidth:26 theText:@"热门话题"];
        [view addSubview:label];
    } else {
        view.backgroundColor = RGBCOLOR(244, 244, 244);
    }
    return view;
}
/// 分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
/// 对应的数据量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.hotDataArray.count;
    }
    return self.dataArray.count;
}
/// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 30;

    }
    id model = self.dataArray[indexPath.row];
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[BBSViewListCell class] contentViewWidth:SCREEN_WIDTH];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    BBSMessageViewController *view = [BBSMessageViewController new];
    if (indexPath.section == 0) {
        view.model = self.hotDataArray[indexPath.row];
    }
    if (indexPath.section == 1) {
        view.model = self.dataArray[indexPath.row];
    }
    [self.navigationController pushViewController:view animated:YES];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BBSViewHotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BBSViewHotCell"];
        if (!cell) {
            cell = [[BBSViewHotCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BBSViewHotCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.model = self.hotDataArray[indexPath.row];
        return cell;
    }
    else {
        BBSViewListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[BBSViewListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        cell.model = self.dataArray[indexPath.row];
        cell.coreTextClick = ^{
            [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
        };
        return cell;
    }
 }
- (void)setupRefreshData {
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.totalCount = 1;
            [self downLodingDate];
            [weakSelf.tableView.mj_header endRefreshing];
        });
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.totalCount ++;
            [self downLodingDate];
            [weakSelf.tableView.mj_footer endRefreshing];
        });
    }];
}
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SCREEN_TabbarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-SCREEN_TabbarHeight-theHeight)style:(UITableViewStyleGrouped)];
        _tableView.delegate        = self;
        _tableView.dataSource      = self;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorColor  = [UIColor clearColor];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}
- (NSMutableArray*)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray*)hotDataArray {
    if (_hotDataArray == nil) {
        _hotDataArray = [NSMutableArray array];
    }
    return _hotDataArray;
}

@end
  
